import { login, logout, getInfo } from 'api/admin'
import { getToken, setToken, removeToken } from 'utils/auth'
const admin = {
  state: {
    token: getToken(),
    name: '',
    avatar: ''
  },
  mutations: {
    'SET_TOKEN': (state, token) => {
      state.token = token
    },
    'SET_NAME': (state, name) => {
      state.name = name
    },
    'SET_AVATAR': (state, avatar) => {
      state.avatar = avatar
    }
  },
  actions: {
    // 登录
    Login ({ commit }, adminInfo) {
      adminInfo.account.trim()
      return new Promise((resolve, reject) => {
        login(adminInfo).then(res => {
          const data = res.data
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取管理员的信息
    GetAdminInfo ({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(res => {
          const data = res.data
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 登出
    Logout ({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          commit('SET_TOKEN', '')
          removeToken()
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 前端登出
    FedLogout ({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    }
  }
}

export default admin
